package com.wlcorp.forcazamis.dao.sample.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibatis.dao.client.DaoException;
import com.wlcorp.forcazamis.dao.sample.ISubSampleDAO;
import com.wlcorp.forcazamis.domain.sample.SubSample;
import com.wlcorp.forcazamis.sys.util.AppConstant;
import com.wlcorp.forcazamis.sys.util.Validator;

public class SubSampleDAOImpl extends HibernateDaoSupport implements
		ISubSampleDAO {

	public void saveSubSample(SubSample subSample) throws DaoException {
		getHibernateTemplate().clear();
		getHibernateTemplate().saveOrUpdate(subSample);
		
	}

	public void deleteSubSample(SubSample subSample) throws DaoException {
		subSample.setDeleteFlag(true);
		getHibernateTemplate().update(subSample);
	}

	public SubSample getSubSampleById(Long subSampleId) throws DaoException {
		return (SubSample)getHibernateTemplate().get(SubSample.class,subSampleId);
	}

	@SuppressWarnings("unchecked")
	public List getSubSampleList(final SubSample subSample) throws DaoException {
		final StringBuffer queryString = new StringBuffer("select subSample from SubSample as subSample where subSample.deleteFlag=false and subSample.flag = ").append(AppConstant.RECORD_UNDELETED);
		if(null != subSample){
			if(Validator.checkValueIsValid(subSample.getSampleCode())){
				queryString.append(" and subSample.parentSample.sampleCode like '%").append(subSample.getSampleCode()).append("%'");
			}
		}
		return getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				if(null != subSample && null != subSample.getMinRownum()){
					query.setFirstResult(subSample.getMinRownum());
					query.setMaxResults(subSample.getNumPerPage());
				}
				return query.list();
			}
		});
	}

	public Long getSubSampleCount(final SubSample subSample) throws DaoException {
		final StringBuffer queryString = new StringBuffer("select count(subSample) from SubSample as subSample where 1=1 and subSample.deleteFlag=false");
		if(null != subSample){
			if(Validator.checkValueIsValid(subSample.getSampleCode())){
				queryString.append(" and subSample.parentSample.sampleCode like '%").append(subSample.getSampleCode()).append("%'");
			}
		}
		return (Long)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				return query.uniqueResult();
			}
		});
	}

}
